package com.yueban.util;

import android.view.View;
import android.view.ViewGroup;
import android.widget.ListAdapter;
import android.widget.ListView;

/**
 * 此工具通过list的children的个数以及每个的高度
 * 来设置listView的高度
 */
public class ListViewHeightUtil {

    public static void setListViewHeightBasedOnChildren(ListView listView) {
        ViewGroup.LayoutParams params = listView.getLayoutParams();
        ListAdapter listAdapter = listView.getAdapter();
        if (listAdapter == null) {
            params.height = 0;
        } else {
            int totalHeight = 0;
            for (int i = 0; i < listAdapter.getCount(); i++) {
                View listItem = listAdapter.getView(i, null, listView);
                listItem.measure(0, 0);
                totalHeight += listItem.getMeasuredHeight();
            }
            params.height = totalHeight
                    + (listView.getDividerHeight() * (listAdapter.getCount() - 1));
        }
        listView.setLayoutParams(params);
    }

}
